# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
import os
import os.path
from configparser import ConfigParser
import requests
from tqdm.rich import tqdm
import warnings

import HOCR_Lib as lib
import HDW as DW
import colorama
import threading
import time
import subprocess
import ctypes
import json
import shutil
import sys

"""
def updata_banlist():
    thr = threading.Thread(target=updata_banlist_main)
    thr.start()
"""

requests.packages.urllib3.disable_warnings()
warnings.simplefilter("ignore")

#Lib
"""
Popularity() -人气 -返回值 str
get_welcome_message() -获取欢迎语 str
copy_and_replace(source_folder, destination_folder) -复制并替换（文件夹） execute
delete(path) -删除某个文件夹（多线程） execute
clear_terminal() -清屏 execute
get_ret() -获取当前程序目录 str
is_admin() -是否是以管理权限运行？ True/False
get_reg (path,name) -获取某个注册表键值 str
WGETH_D_N(RUL, Path) -下载一个huang1111云盘的文件(NoGUI) execute
WGETH_D(RUL, Path) -下载一个huang1111云盘的文件 execute
WGET_D(RUL, Path, Name) -下载一个文件 execute
"""

#常量
V="0.0.4"
UP="[+] 安装/卸载 时的自定义命令\n[+] 新增安装检查，如：智齿仅智齿x64/x32端\n[=] 优化目录逻辑\n[=] 修复已知问题"
TITLE = """
                               
 _____ _____ _____ _____ _____ 
|  _  |  |  |     |     | __  |
|   __|     |  |  |   --|    -|
|__|  |__|__|_____|_____|__|__|
                               
"""
DEV = "daijunhao - 部分Lib， Hypixice - 主要程序"

main_menu_list = ["安装","卸载","关于/更新内容(包含Packer的更新内容)"]
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
}


#LIB 
"""
DW.WGET_D(链接, 线程数, 路径, 文件名) #下载huang111文件 execute
"""

"""def op(out,put):
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    if put == "1":
        print(f"[Information：{current_time}] {out}" + colors.ENDC)
    elif put == "2":
        print(colors.GREEN + f"[Success：{current_time}] " + colors.ENDC + str(out))
    elif put == "3":
        print(colors.FAIL + f"[Error：{current_time}] " + colors.ENDC + str(out))
    elif put == "4":
        print(colors.WARNING + f"[WARNING：{current_time}] " + colors.ENDC + str(out))"""

def set_terminal_title(title):
    ctypes.windll.kernel32.SetConsoleTitleW(title)

class colors:
    HEADER = colorama.Fore.RESET
    BLUE = colorama.Fore.LIGHTCYAN_EX
    GREEN = colorama.Fore.LIGHTGREEN_EX
    WARNING = colorama.Fore.LIGHTYELLOW_EX
    FAIL = colorama.Fore.LIGHTRED_EX
    ENDC = colorama.Fore.RESET
    UNDERLINE = colorama.Fore.RESET
    RESET = colorama.Fore.RESET
    INOF = colorama.Fore.LIGHTWHITE_EX

#清屏
def cls():   
    os.system("cls")
    
#加载动画
def wt(text, stop_event):
    # 保存文本的长度用于清理行
    text_length = len(text)
    
    while not stop_event.is_set():
        print(f"{colors.GREEN}- {colors.ENDC}{text}", end="\r")
        time.sleep(0.1)
        print(f"{colors.GREEN}\\ {colors.ENDC}{text}", end="\r")
        time.sleep(0.1)
        print(f"{colors.GREEN}| {colors.ENDC}{text}", end="\r")
        time.sleep(0.1)
        print(f"{colors.GREEN}/ {colors.ENDC}{text}", end="\r")
        time.sleep(0.1)
    
    # 清理输出
    print(" " * (text_length + 5), end="\r")
    print(" " * (text_length + 5), end="\r")
    print(" " * (text_length + 5), end="\r")
    print("", end="\r")
    

def update_check(json, Ver):
    #requests.get(RUL)
    if json["Version"] != Ver:
        return True
    else:
        return False
    
    
#更合理的删除
def del_path_a(source_folder_path, target_folder_path):
    # 获取源目录中所有文件的相对路径
    source_files = set()
    for root, dirs, filenames in os.walk(source_folder_path):
        for filename in filenames:
            source_files.add(os.path.relpath(os.path.join(root, filename), source_folder_path))
    
    # 遍历目标目录
    for root, dirs, filenames in os.walk(target_folder_path, topdown=False):
        for filename in filenames:
            # 构建目标文件的相对路径
            target_file = os.path.relpath(os.path.join(root, filename), target_folder_path)
            if target_file in source_files:
                # 删除匹配的文件
                os.remove(os.path.join(root, filename))
                lib.op(f"Deleted file: {os.path.join(root, filename)}","1")
        
        # 删除空目录
        if not os.listdir(root):
            os.rmdir(root)
            lib.op(f"Deleted empty directory: {root}","1")




#询问路径
def load_path():
    cls()
    if MC_Version_Check == "x32":
        if os.path.exists(netease + "\\windowsmc"):
            path = netease + "\\windowsmc"
            return path
        else:
            print(f"{colors.WARNING}[!] {colors.ENDC}未检测到x32版本，如需支持所有版本请将更改配置文件！")
            input()
            exit()
    if MC_Version_Check == "x64":
        if os.path.exists(netease + "\\x64_mc"):
            path = netease + "\\x64_mc"
            return path
        else:
            print(f"{colors.WARNING}[!] {colors.ENDC}未检测到x64版本，如需支持所有版本请将更改配置文件！")
            input()
            exit()
    elif MC_Version_Check == "All":
        print(f"======= {colors.WARNING}选择目录 {colors.ENDC}=======\n{colors.WARNING}[!] {colors.ENDC}请选择你要安装/卸载的目录\n\n{colors.WARNING}[1]{colors.ENDC} Netease({netease})\n{colors.WARNING}[2]{colors.ENDC} 4399({p4399})\n{colors.WARNING}[3]{colors.ENDC} 自定义\n")
        key = input("请输入一个序号：")
        if key == "1":
            if os.path.exists(netease):
                if os.path.exists(netease + "\\windowsmc"):
                    path = netease + "\\windowsmc"
                if os.path.exists(netease + "\\x64_mc"):
                    path = netease + "\\x64_mc"
                    
                if os.path.exists(netease + "\\x64_mc"):
                    if os.path.exists(netease + "\\windowsmc"):
                        cls()
                        print(f"{colors.FAIL}[!] {colors.ENDC}检测到两个目录，请手动选择一个目录\n{colors.WARNING}[1]{colors.ENDC} windowsmc(x86)\n{colors.WARNING}[2]{colors.ENDC} x64_mc(x64)\n")
                        key = input("请输入一个目录：")
                        if key == "1":
                            path = netease + "\\windowsmc"
                            
                        elif key == "2":
                            path = netease + "\\x64_mc"
                            
                        else:
                            print(f"{colors.FAIL}[!] {colors.ENDC}输入错误，按下回车重新选择")
                            input()
                            load_path()
                return path
                            
        elif key == "2":
            if os.path.exists(p4399):
                if os.path.exists(p4399 + "\\windowsmc"):
                    path = p4399 + "\\windowsmc"
                    
                if os.path.exists(p4399 + "\\x64_mc"):
                    path = p4399 + "\\x64_mc"
                    
                if os.path.exists(p4399 + "\\x64_mc"):
                    if os.path.exists(p4399 + "\\windowsmc"):
                        cls()
                        print(f"{colors.FAIL}[!] {colors.ENDC}检测到两个目录，请手动选择一个目录\n{colors.WARNING}[1]{colors.ENDC} windowsmc(x86)\n{colors.WARNING}[2]{colors.ENDC} x64_mc(x64)\n")
                        key = input("请输入一个目录：")
                        if key == "1":
                            path = p4399 + "\\windowsmc"
                            
                        elif key == "2":
                            path = p4399 + "\\x64_mc"
                            
                        else:
                            print(f"{colors.FAIL}[!] {colors.ENDC}输入错误，按下回车重新选择")
                            input()
                            load_path()
                return path
            
        elif key == "3":
            cls()
            print(f"======= {colors.WARNING}自定义目录 {colors.ENDC}=======\n{colors.WARNING}[!] {colors.ENDC}请输入你要安装/卸载的目录(如：C:\MCLDownload\MinecraftBENetease)\n")
            path = input("请输入目录：")
            if os.path.exists(path):
                if os.path.exists(path + "\\windowsmc"):
                    path_ = path + "\\windowsmc"
                    
                if os.path.exists(path + "\\x64_mc"):
                    path_ = path + "\\x64_mc"
                    
                if os.path.exists(path + "\\x64_mc"):
                    if os.path.exists(path + "\\windowsmc"):
                        cls()
                        print(f"{colors.FAIL}[!] {colors.ENDC}检测到两个目录，请手动选择一个目录\n{colors.WARNING}[1]{colors.ENDC} windowsmc(x86)\n{colors.WARNING}[2]{colors.ENDC} x64_mc(x64)\n")
                        key = input("请输入一个目录：")
                        if key == "1":
                            path_ = path + "\\windowsmc"
                            
                        elif key == "2":
                            path_ = path + "\\x64_mc"
                            
                        else:
                            print(f"{colors.FAIL}[!] {colors.ENDC}输入错误，按下回车重新选择")
                            input()
                            load_path()
                return path_
            else:
                print(f"{colors.FAIL}[!] {colors.ENDC}目录不存在，按下回车重新选择")
                input()
                load_path()
        
        else:
            print(f"{colors.FAIL}[!] {colors.ENDC}输入错误，按下回车重新选择")
            input()
            load_path()
    else:
        print(f"{colors.FAIL}[!] {colors.ENDC}配置文件配置错误，仅可以是x64/x32/All")
        input()
        load_path()
        
#安装    
def install():
    print(f"======= {colors.WARNING}安装 {colors.ENDC}=======\n{colors.FAIL}[!] {colors.ENDC}你确定要继续吗？\n\n{colors.WARNING}[1]{colors.ENDC} 是\n{colors.WARNING}[2]{colors.ENDC} 否\n")
    key = input("请输入一个序号：")
    if key == "1":
        cls()
        path = load_path()
        if path == "":
            lib.op("目录不存在或设置错误，按任意键返回主菜单...","3")
            input()
            main_menu()
        cls()
        print(f"{colors.WARNING}[Debuger] {colors.ENDC}{path}")
        lib.op("开始安装...\n","1")
        stop_event = threading.Event()
        thr = threading.Thread(target=wt, args=("正在安装，请稍等...", stop_event))
        thr.start()
        
        if ENBREPCMD == "True" and rawdata["Packer_Replace_cmd"]["Replace_Install_cmd"] != []:
            lib.op("执行安装命令...","1")
            for cmd in rawdata["Packer_Replace_cmd"]["Replace_Install_cmd"]:
                exec(cmd)
            lib.op("自定义命令已执行完成","2")
        else:
            pass
            lib.op("未找到安装命令，已跳过","1")
        #start
        lib.copy_and_replace(f"{ret}\\Packer\\Master", path)
        if os.path.isfile(f"{path}\\data\\resource_packs\\vanilla_netease\\contents.json"):
            lib.op("删除字典中...","1")
            os.remove(f"{path}\\data\\resource_packs\\vanilla_netease\\contents.json")
        else:
            pass
            lib.op("找不到字典，已跳过","1")
            
        time.sleep(2)
        stop_event.set()  
        thr.join()  
        lib.op("安装完成，按任意键返回主菜单...","2")
        input()
        main_menu()
        
    elif key == "2":
        lib.op("已取消安装,按任意键返回主菜单...","4")
        input()
        main_menu()
    else:
        lib.op("输入错误，按任意键返回主菜单...","3")
        input()
        main_menu()
        
        
#卸载
def uninstall():
    print(f"======= {colors.WARNING}卸载 {colors.ENDC}=======\n{colors.FAIL}[!] {colors.ENDC}你确定要继续吗？\n\n{colors.WARNING}[1]{colors.ENDC} 是\n{colors.WARNING}[2]{colors.ENDC} 否\n")
    key = input("请输入一个序号：")
    if key == "1":
        cls()
        path = load_path()
        if path == "":
            lib.op("目录不存在或设置错误，按任意键返回主菜单...","3")
            input()
            main_menu()
        cls()
        lib.op("开始卸载...\n","1")
        stop_event = threading.Event()
        thr = threading.Thread(target=wt, args=("正在卸载，请稍等...", stop_event))
        thr.start()
        if ENBREPCMD == "True" and rawdata["Packer_Replace_cmd"]["Replace_Uninstall_cmd"] != []:
            lib.op("执行安装命令...","1")
            for cmd in rawdata["Packer_Replace_cmd"]["Replace_Uninstall_cmd"]:
                exec(cmd)
            lib.op("自定义命令已执行完成","2")
        else:
            pass
            lib.op("未找到安装命令，已跳过","1")
        #start
        source_dir = f"{ret}\\Packer\\Master"
        target_dir = f"{path}\\"
        try:
            del_path_a(source_dir, target_dir)
        except Exception as e:
            print(e)
            pass
        #lib.delete(f"{path}\\data\\resource_packs\\vanilla_netease\\sounds")
        #lib.delete(f"{path}\\data\\resource_packs\\vanilla_netease\\texts")
        time.sleep(2)
        
        stop_event.set()  
        thr.join()  
        lib.op("卸载完成，按任意键返回主菜单...","2")
        input()
        main_menu()
        
    elif key == "2":
        lib.op("已取消卸载,按任意键返回主菜单...","4")
        input()
        main_menu()
    else:
        lib.op("输入错误，按任意键返回主菜单...","3")
        input()
        main_menu()


def Adds_menu():
    Adds_menu = load_path()
    cls()
    print(f"======= {colors.WARNING}附加包 {colors.ENDC}=======\n{colors.FAIL}[!] {colors.ENDC}选择一个模式\n\n{colors.WARNING}[1]{colors.ENDC} 新增\n{colors.WARNING}[2]{colors.ENDC} 删除\n")
    key = input("请输入一个序号：")
    if key == "1":
        Mode = "add"
    elif key == "2":
        Mode = "del"
    else:
        lib.op("输入错误，按任回车重写...","3")
        input()
        Adds_menu()
    while True:
        cls()
        print(f"================ {colors.WARNING}附加包 {colors.ENDC}===================\n\n{colors.GREEN}[!] {colors.ENDC}当前模式: {colors.BLUE}{Mode}{colors.ENDC}\n\n")
        #print(Adds_menu_list)
        for i in range(len(Adds_menu_list)):
            #print({Adds_menu_list[i]})
            print(f"{colors.WARNING}[{i+1}] {colors.ENDC}{Adds_menu_list[i]}")
        print(f"{colors.WARNING}[{len(Adds_menu_list)+1}] {colors.ENDC}返回主菜单\n")
        key = input(f"请输入一个序号：")
        cls()        
        try:
            if int(key) <= len(Adds_menu_list) + 1:
                if int(key) == len(Adds_menu_list) + 1:
                    main_menu()
                else:
                    if Mode == "add":
                        stop_event = threading.Event()
                        thr = threading.Thread(target=wt, args=("开始执行", stop_event))
                        thr.start()
                        for i in rawdata["Packer_Adds"][0]["Install_Cmd"]:
                            exec(i)
                        stop_event.set()  
                        thr.join()
                        lib.op("执行完成，按任意键返回附加包菜单...","2")
                        input()
                    elif Mode == "del":
                        stop_event = threading.Event()
                        thr = threading.Thread(target=wt, args=("开始执行", stop_event))
                        thr.start()
                        for i in rawdata["Packer_Adds"][0]["Uninstall_Cmd"]:
                            exec(i)
                        stop_event.set()
                        thr.join()
                        lib.op("执行完成，按任意键返回附加包菜单...","2")
                        input()
                    else:
                        lib.op("未知错误，请检查配置文件","3")
                        input()
                        
            else:
                lib.op("输入错误，按任回车重写...","3")
                input()
        except Exception as e:
            lib.op(f"输入错误，或包配置错误，按任回车重写...\n{e}","3")
            input()
        
    



#初始化
ret = lib.get_ret()
netease, p4399 = "", ""
#获取注册表
try:
    #get netease
    netease = lib.get_reg(r"Software\Netease\MCLauncher", "MinecraftBENeteasePath")
    print(netease)
except Exception as e:
    pass

try:
    #get 4399
    p4399 = lib.get_reg(r"Software\Netease\PC4399_MCLauncher", "MinecraftBENeteasePath")
    print(p4399)
except Exception as e:
    pass

if netease != "" or p4399 != "":
    pass
else:
    lib.op("未检测到任何启动器，请先安装网易或4399启动器. 请进入主页后设置自定义目录。","3")
    input()
#Main 
cls()

def main_menu():
    cls()
    ad =""
    if ENUPDATE == "True":
        ad = f"Packer Announcement: {UPDATANO}"
    
    msg = lib.get_welcome_message()
    po = lib.Popularity()
    if ENADDS == "True" or ENBREPCMD == "True":
        print(f"================ {colors.WARNING}Public Hypixice One Click Replacement {colors.BLUE}{V} {colors.ENDC}===================\n{colors.BLUE}{PACKERTITLE}{colors.ENDC}\nPacker Name: {PACKERNAME}\nPacker Info: {PACKINFO}\nPacker Version: {PACKERVER}\nPacker Author: {PACKAUTHOR}\n{ad}\n\n==================================================================================================================\n{colors.FAIL}[!] {colors.ENDC}本材质包已启用脚本。\n请注意，安装，或附加包 中执行的代码完全由材质包创建者提供和控制。因此，程序作者不对附加包可能带来的任何问题或风险负责。\n================================================================================================================== \n\n\n{msg}\n{po}\n\n")
    else:
        print(f"================ {colors.WARNING}Public Hypixice One Click Replacement {colors.BLUE}{V} {colors.ENDC}===================\n{colors.BLUE}{PACKERTITLE}{colors.ENDC}\nPacker Name: {PACKERNAME}\nPacker Info: {PACKINFO}\nPacker Version: {PACKERVER}\nPacker Author: {PACKAUTHOR}\n{ad}\n\n\n{msg}\n{po}\n\n")
    for i in range(len(main_menu_list)):
        print(f"{colors.WARNING}[{i+1}] {colors.ENDC}{main_menu_list[i]}")
    print("\n")
        
    
    key = input(f"请输入一个序号：")
    if key == "1":
        cls()
        install()
    elif key == "2":
        cls()
        uninstall()
    elif key == "3" and ENADDS == "False":
        cls()
        print(f"================ {colors.WARNING}关于/更多信息 {colors.ENDC}===================\n\n程序信息:\n\n{colors.WARNING}Public Hypixice One Click Replacement {colors.BLUE}{V} {colors.ENDC}\n\n\n更新记录:\n\n{UP}\n\n\n开发者: \n\n{DEV}\n\n\nPacker 信息:\n{colors.BLUE}{PACKERTITLE}{colors.ENDC}\nPacker Name: {PACKERNAME}\nPacker Version: {PACKERVER}\nPacker 更新记录: {PACKERUP}\nPacker Author: {PACKAUTHOR}\n\n\n{colors.WARNING}\n")
        input("\n>>> 按回车返回 <<<")
        main_menu()

    elif key == "3" and ENADDS == "True":
        cls()
        Adds_menu()
    elif key == "4" and ENADDS == "True":
        cls()
        print(f"================ {colors.WARNING}关于/更多信息 {colors.ENDC}===================\n\n程序信息:\n\n{colors.WARNING}Public Hypixice One Click Replacement {colors.BLUE}{V} {colors.ENDC}\n\n\n更新记录:\n\n{UP}\n\n\n开发者: \n\n{DEV}\n\n\nPacker 信息:\n{colors.BLUE}{PACKERTITLE}{colors.ENDC}\nPacker Name: {PACKERNAME}\nPacker Version: {PACKERVER}\nPacker 更新记录: {PACKERUP}\nPacker Author: {PACKAUTHOR}\n\n\n{colors.WARNING}\n")
        input("\n>>> 按回车返回 <<<")
        main_menu()
    else:
        main_menu()
#Start

def start_main():
    global PACKAUTHOR, PACKINFO, PACKERNAME, PACKERVER, PACKERTITLE, ENADDS, PACKERUP, main_menu_list, Adds_menu_Cmd_list, Adds_menu_info_list, UPDATAJSON, UPDATAMODED, ENADDS, ENUPDATE, UPDATARUL, UPDATANO, Adds_menu_list, rawdata, MC_Version_Check, ENBREPCMD
    set_terminal_title(f"PHOCR [{V}]")
    if not lib.is_admin():
        lib.op("请以管理员身份运行本程序","3")
        input()
        sys.exit()
        


    #Loadjson
    cls()
    lib.op("Loading Packer Config...","1")
    try:
        with open(f"{ret}\\Packer\\config.json", 'r', encoding='utf-8') as file:
            rawdata = json.load(file)
            
        stop_event = threading.Event()
        thr = threading.Thread(target=wt, args=("Initialize Engine...", stop_event))
        thr.start()
        print(f"{colors.WARNING}[Debuger] {colors.ENDC}{rawdata}")
        #Load json
        PACKERNAME = rawdata["Packer_info"]["Name"]
        PACKERVER = rawdata["Packer_info"]["Version"]
        PACKERTITLE = rawdata["Packer_info"]["Title"]
        PACKAUTHOR = rawdata["Packer_info"]["Author"]
        PACKINFO = rawdata["Packer_info"]["Packer_Info"]
        ENADDS = rawdata["Packer_info"]["Enable_Adds"]
        PACKERUP = rawdata["Packer_info"]["Update_Content"]
        MC_Version_Check = rawdata["Packer_info"]["MC_Version_Check"]
        ENBREPCMD = rawdata["Packer_Replace_cmd"]["Enable"]
        
        if rawdata["Packer_info"]["Enable_Check_Update"] == "True":
            ENUPDATE = "True"
            UPDATARUL = rawdata["Packer_info"]["Update_RUL"]
            UPDATAMODED = rawdata["Packer_info"]["Update_Mode"]
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er Update_Check is enabled, Update_RUL: {UPDATARUL}, Update_Mode: {UPDATAMODED}")
            
        else:
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er Update_Check is disabled.")
        
            
        if rawdata["Packer_info"]["Enable_Adds"] == "True":
            main_menu_list = ["安装","卸载","附加包管理","关于/更新内容(包含Packer的更新内容)"]
            Adds_menu_list, Adds_menu_info_list, Adds_menu_Cmd_list = [],[],[]
            for i in range(len(rawdata["Packer_Adds"])):            
                Adds_menu_list.append(rawdata["Packer_Adds"][i]["Adds_name"])       
                print(f"{colors.WARNING}[Debuger] {colors.BLUE}Packer.load.name: {colors.ENDC}" + rawdata["Packer_Adds"][i]["Adds_name"])
                Adds_menu_info_list.append(rawdata["Packer_Adds"][i]["Adds_info"])
                print(f"{colors.WARNING}[Debuger] {colors.BLUE}Packer.load.Adds_info: {colors.ENDC}" + rawdata["Packer_Adds"][i]["Adds_info"])
                
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er adds is enabled.")
        else:
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er adds is disabled.")
            
        
        if rawdata["Packer_Replace_cmd"]["Enable"] == "True":
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er Replace_cmd is enabled.")
        else:
            print(f"{colors.WARNING}[Debuger] {colors.ENDC}Pack.er Replace_cmd is disabled.")
            
            
        
        
    except FileNotFoundError:
        lib.op(f"文件 {ret}\\Packer\\config.json 不存在。","3")
        input()
        sys.exit()
    except json.JSONDecodeError:
        lib.op("读取 JSON 文件时出错。","3")
        input()
        sys.exit()
        
    except Exception as e:
        lib.op(f"哦，你遇到了预料外的严重错误，这可能是Packer文件配置错误导致的，错误信息: {e}","3")
        input()
        sys.exit()
        
    #Check Update
    lib.op("Start Check Packer Version...","1")
    if ENUPDATE == "True":
        try:
            UPDATAJSON = json.loads(requests.get(f"{UPDATARUL}", headers=headers, verify=False).text)
            print(f"{colors.WARNING}[Debugger] {colors.ENDC}Rawtext: {UPDATAJSON}")
            UPDATANO = UPDATAJSON["Notice"] 
            if update_check(UPDATAJSON, PACKERVER) == True:
                stop_event.set()  
                thr.join()  
                cls()
                print(f"{colors.WARNING}[INFO] {colors.ENDC}Packer Update is available.")
                key = input(f"{colors.WARNING}[INFO] {colors.ENDC}已有新的Packer更新可用,是否更新？ \n更新内容：\n{UPDATAJSON['Update']}\n(Y/N)")
                if key == "Y" or key == "y":
                    # cls()
                    command = [
                        f"{ret}\\Runtime\\bz.exe",
                        "x",
                        "-aoa",
                        f"-o:{ret}",
                        f"{ret}\\Runtime\\DW\\Packer.zip"
                    ]
                    cls()
                    if UPDATAMODED == "Huang111":
                        DW.WGET_D(f"{UPDATAJSON['Download']}", "32", f"{ret}\\Runtime\\DW", "Packer.zip")
                        cls()
                        print("下载完成")
                        lib.delete(f"{ret}\\Packer")
                        subprocess.Popen(command,stdout=subprocess.PIPE, universal_newlines=True, encoding="utf-8")
                        lib.op("更新完成，按回车继续", "2")
                        input()
                        
                    else:
                        lib.WGET_D_N(f"{UPDATAJSON['Download']}", "32", f"{ret}\\Runtime\\DW", "Packer.zip")
                        cls()
                        print("下载完成")
                        lib.delete(f"{ret}\\Packer")
                        subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True,encoding="utf-8")
                        lib.op("更新完成，按回车继续", "2")
                        input()
                else:
                    lib.op("已取消更新，按回车继续", "4")
                    input()
                        
        except Exception as e:
            lib.op(f"哦，你遇到了预料外的严重错误，这可能是Packer文件配置错误,或云端json设置错误导致的，错误信息: {e}","3")
            input()
            sys.exit()


    stop_event.set()  
    thr.join()  

    cls()
    print(f"{colors.BLUE}{TITLE}\n{colors.ENDC}欢迎使用PHOCR {V}\n\n作者: Hypixice\n交流/BUG反馈: 613015467\n\n{colors.FAIL}[!] {colors.ENDC}确定要进入程序吗？进入会关闭游戏进程！\n\n{colors.WARNING}[1]{colors.ENDC} 是\n{colors.WARNING}[2]{colors.ENDC} 否\n")
    key = input("请输入一个序号：")
    if key == "1":
        subprocess.run(['taskkill', '/F', '/IM', 'Minecraft.Windows.exe'])
        cls()
        main_menu()
    elif key == "2":
        lib.op("已取消安装,按任意键退出","4")
        input()
        sys.exit()
    else:
        cls()
        lib.op("输入错误，按任意键退出","3")
        input()
        sys.exit()
        
if __name__ == "__main__":
    start_main()
